<?php

namespace app\api\controller;

use app\admin\model\factor\CarbonFactor;
use app\admin\model\template\Template;
use app\api\service\shop\AccountTemplateService;
use app\api\service\shop\CarbonFactorService;
use app\api\service\shop\CarouselService;
use app\api\service\shop\FactorCollectionService;
use app\api\service\shop\SearchService;
use app\api\validate\ShopValidate;


/**
 * 商城首页控制器
 */
class ShopIndex extends Base
{
    protected $noNeedRight = ['getFactorDatabaseList', 'getCarouseList', 'getAccountTemplateList', 'search', 'getAccountTemplateInfo', 'getSearchHistory', 'collection', 'cancelCollection'];
    private SearchService $searchService;
    private CarouselService $carouselService;
    private FactorCollectionService $factorService;
    private CarbonFactorService $carbonFactorService;
    private AccountTemplateService $accountTemplateService;

    public function __construct(SearchService $searchService, CarouselService $carouselService, FactorCollectionService $factorService, AccountTemplateService $accountTemplateService, CarbonFactorService $carbonFactorService, ShopValidate $validate)
    {
        parent::__construct();
        $this->searchService = $searchService;
        $this->factorService = $factorService;
        $this->carouselService = $carouselService;
        $this->carbonFactorService = $carbonFactorService;
        $this->accountTemplateService = $accountTemplateService;
        $this->validate = $validate;
    }

    /**
     * 获取因子数据库列表
     */
    public function getFactorDatabaseList()
    {
        $userId = intval($this->auth->id);
        $data = $this->request->post();
        $this->valid($data, 'factor');
        $data = CarbonFactor::where('status', 1)
            ->where(function ($query) use ($data) {
                if (!empty($data['content'])) {
                    $query->where('name', 'like', '%' . $data['content'] . '%')
                        ->whereOr('sn', $data['content']);
                }
                if (!empty($data['category_id'])) {
                    $query->where('category_id', $data['category_id']);
                }
            })
            ->field(['id', 'name', 'lifecycle', 'user_id', 'carbon_factor_result_kg carbon_result', 'unit', 'is_account', 'is_authority', 'sn', 'sales'])
            ->order(['sales' => 'desc', 'id' => 'desc'])
            ->paginate($data['limit'] ?? 15)
            ->each(function ($item) use ($userId) {
                $item->auth = $item->is_authority == 1 ? '权威性认证' : ($item->is_account == 1 ? '核算结果认证' : null);
                $item->append(['company_name']);
                $item->is_collection = !empty($item->collection()->where(['user_id' => $userId, 'factor_id' => $item->id])->count('user_id'));
            });
        $this->success('ok', ['total' => $data->total(), 'row' => $data->items()]);
    }

    /**
     * 获取核算模板列表
     */
    public function getAccountTemplateList()
    {
        $data = $this->request->get();
        $this->valid($data, 'template');

        $data = Template::where('status', 1)
            ->where(function ($query) use ($data) {
                if (!empty($data['content'])) {
                    $query->where('product_name', 'like', '%' . $data['content'] . '%')
                        ->whereOr('sn', $data['content']);
                }
                if (!empty($data['group_id'])) {
                    $query->where('group_id', $data['group_id']);
                }
                if (!empty($data['category_id'])) {
                    $query->where('category_id', $data['category_id']);
                }
            })
            ->field(['id', 'thumbnail', 'user_id','product_name', 'price', 'product_id', 'sales'])
            ->order('sales', 'desc')
            ->order('id','desc')
            ->paginate($data['limit'] ?? 15)
            ->each(function ($item) {
                $item->append(['product_sn','company_name']);
            });
        $this->success('ok', ['total' => $data->total(), 'row' => $data->items()]);
    }

    /**
     * 搜索
     */
    public function search()
    {
        $data = $this->request->get();
        $this->valid($data, 'search');
        $userId = intval($this->auth->id);
        $this->success('ok', $this->searchService->search($data['typeId'], $data['content'], $data['page'], $data['limit'], $userId));
    }

    /**
     * 收藏因子
     */
    public function collection()
    {
        $userId = intval($this->auth->id);
        $data = $this->request->post();
        $this->valid($data, 'collection');
        $factorId = intval($data['factorId']);
        $this->antiShake($userId, $factorId, 3, null, '请勿频繁收藏');
        $message = $this->factorService->factorCollection($userId, $factorId);
        empty($message) ? $this->success('收藏成功') : $this->error($message);

    }

    /**
     * 取消收藏因子
     */
    public function cancelCollection()
    {
        $userId = intval($this->auth->id);
        $data = $this->request->post();
        $this->valid($data, 'collection');
        $factorId = intval($data['factorId']);
        $this->antiShake($userId, $factorId, 3, null, '请勿频繁取消收藏');
        $message = $this->factorService->cancelFactorCollection($userId, $factorId);
        empty($message) ? $this->success('取消收藏成功') : $this->error($message);
    }

    /**
     * 获取核算模板详情
     */
    public function getAccountTemplateInfo()
    {
        $data = $this->request->get();
        $this->valid($data, 'info');
        $userId = intval($this->auth->id);
        $template = $this->accountTemplateService->getTemplateInfo($data['id']);
        if (!$template) {
            $this->error('当前商品不存在, 请重新选择');
        }

        if ($this->auth->id != $template->user_id) {
            if ($template->status != 1) {
                $this->error('当前商品不存在, 请重新选择');
            }
        }
        $order = \app\admin\model\template\Order::where(['user_id' => $userId])
            ->whereIn('pay_state', [0, 1])
            ->where('template_id', $template->id)
            ->order('id', 'desc')->field(['order_sn', 'pay_state', 'pay_state pay_state_id'])
            ->find();
        $template->order = $order;
        $oldSnap = $template->snapshot;
        $template->snapshot = $this->buildTree($oldSnap);
        $template->snapshot_slice = $this->buildTreeSlice($oldSnap);
        $this->success('ok', $template);
    }

    /**
     * 获取搜索历史
     */
    public function getSearchHistory()
    {
        $userId = intval($this->auth->id);
    }

    public function getCarouseList()
    {
        $this->success('ok', $this->carouselService->getCarouseList());
    }
}